package org.dtrd.config.filter;

import org.dtrd.common.constant.CommonConstant;
import org.dtrd.config.sign.util.BodyReaderHttpServletRequestWrapper;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Iterator;

/**
 * @author xiao
 * @date 2022/9/22 9:32 AM
 */
public class MyDispatcher extends DispatcherServlet {

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Enumeration<String> headerNames = request.getHeaderNames();
        StringBuilder headers = new StringBuilder();
        headers.append("\n");
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.append(headerName).append(" = ").append(request.getHeader(headerName)).append("\n");
        }
        headers.append("\n");
        System.out.println("MyDispatcher.doDispatch getQueryString=" + request.getQueryString() + "; getRequestURI=" + request.getRequestURI() + "; getRequestURL=" + request.getRequestURL() + "; getPathInfo=" + request.getPathInfo() + "; headers=" + headers);
        HttpServletRequest requestWrapper = null;

        HttpServletRequest req = request;
        // POST请求类型，才获取POST请求体
        if (CommonConstant.HTTP_POST.equals(req.getMethod())) {
            requestWrapper = new BodyReaderHttpServletRequestWrapper(req);
        }
        super.doDispatch(requestWrapper != null ? requestWrapper : request, response);
    }
}
